package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class CWDHandle implements Handle {
	FtpSession ftpSession;

	public CWDHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String dir=line.substring(line.indexOf(" "));
		if(dir==null||dir.trim().length()<=0){
			os.write(("550 Requested action not taken.\r\n").getBytes());
			os.flush();
			return;
		}
		dir=dir.trim();
		dir=dir.replace("//", "/");
		String path = PathConvert.toServerPath(ftpSession.getRootDir(), dir);
		File file = new File(path.trim());
		if(!file.exists()){
			os.write(("550 File unavailable.\r\n").getBytes());
			os.flush();
			return;
		}
		if(dir.startsWith("/")){
			ftpSession.currentDir=dir;
		}else{
			ftpSession.currentDir=ftpSession.currentDir+"/"+dir;
		}
		os.write(("250 Directory changed to "+ftpSession.currentDir+"\r\n").getBytes());
		os.flush();
	}
}
